<template>
    <Modal
        title="缴费记录"
        :value="show"
        width="860"
        @on-visible-change="setVisibility">

        <div class="margin-bottom-20" v-if="home">
            <b>{{home.detail_address}} / {{(home.home_no && home.home_no.home_no) || ''}}</b>
        </div>

        <Table :loading="loading" :columns="columns" :data="tableData"></Table>

        <Page
            :current.sync="pagination.page"
            :total="pagination.total"
            :page-size="pagination.page_size"
            show-total
            style="text-align:center"
            @on-change="initData"></Page>

        <div slot="footer"></div>
    </Modal>
</template>

<script>
import { http, api } from '@/libs/http'
import { date, chargeMode } from '@/filters'
export default {
  name: 'home-bills-history',
  props: {
    home: Object,
    show: Boolean
  },
  data () {
    return {
      loading: false,
      tableData: [],
      pagination: {
        page: 1,
        page_size: 10,
        total: 1
      },
      billStatus: {
        1: '已创建',
        2: '已关闭',
        3: '处理中',
        4: '缴费成功',
        5: '清算后退款',
        6: '缴费失败'
      },
      columns: [
        {
          title: '时间',
          width: 180,
          render: (h, p) => <span>{date(p.row.created_at, 'YYYY-MM-DD HH:mm')}</span>
        },
        {
          title: '账号金额',
          key: 'amount'
        },
        {
          title: '缴费模式',
          render: (h, p) => <span>{chargeMode(p.row.charge_mode)}</span>
        },
        {
          title: '状态',
          render: (h, p) => <span>{this.billStatus[p.row.bill_status]}</span>
        }
      ]
    }
  },
  watch: {
    show (n) {
      if (n) {
        this.initData()
      } else {
        this.pagination.page = 1
        this.pagination.total = 1
        this.tableData = []
      }
    }
  },
  methods: {
    setVisibility (val) {
      this.$emit('update:show', val)
    },
    async initData () {
      try {
        this.loading = true
        const data = {
          page: this.pagination.page,
          page_size: this.pagination.page_size,
          home_id: this.home.id
        }
        const res = await http.req(api.agency_home_bills, null, data)
        this.pagination.total = res.count
        const result = res.rows.reduce((arr, next) => {
          return arr.concat(next.bill_insts)
        }, [])
        this.tableData = result
      } catch (err) {
        console.log(err)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>